<template>
  <el-container class="login-layout">
    <el-card class="box-card">
      <div slot="header">
        <h3 class="login-title">欢迎登录</h3>
      </div>
      <el-form ref="loginForm"
               label-position="top"
               :model="form"
               :rules="rules"
               label-width="80px"
               class="login-box">
        <el-form-item label="账号"
                      prop="account">
          <el-input type="text"
                    placeholder="请输入账号"
                    v-model="form.account" />
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input type="password"
                    placeholder="请输入密码"
                    v-model="form.password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-container>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  title: '登录',
  data () {
    return {
      form: {
        account: '',
        password: ''
      },
      rules: {
        account: [
          { required: true, message: '账号不可为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不可为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters('login', ['logined'])
  },
  created () {
    if (this.logined === true) {
      this.redirectHome()
    }
  },
  methods: {
    ...mapActions('login', ['token']),
    async login () {
      await this.$refs.loginForm.validate()
      await this.token(this.form)
      this.$message.success('登录成功')
    },
    redirectHome () {
      this.$router.push({ path: '/' })
    }
  },
  watch: {
    logined (newVal, oldVal) {
      if (newVal === true) {
        this.redirectHome()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-layout {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.box-card {
  margin-top: -80px;
}
.login-title {
  text-align: center;
  margin: 0;
}
.login-box {
  text-align: left;
  min-width: 500px;
}
</style>
